﻿using Nasty.Core.Session;
using Nasty.Core.Entity;
using SqlSugar;
using Nasty.Core.SuperExtension;
using Nasty.Core.Attributes;

namespace Nasty.Core.Entity.Flow
{
    [SugarTable("SysFlowConfig", TableDescription = "流程配置")]
    public class FlowConfig : StandardEntity<FlowConfig>
    {
        /// <summary>
        /// 名称
        /// </summary>
        [NastyColumn(ColumnName = "Name", ColumnDescription = "名称", Required = true)]
        public string? Name { get; set; }

        /// <summary>
        /// 编码
        /// </summary>
        [NastyColumn(ColumnName = "Code", ColumnDescription = "编码", IsRepeat = true)]
        public string? Code { get; set; }

        /// <summary>
        /// 流程触发器
        /// </summary>
        [NastyColumn(ColumnName = "FlowAction", ColumnDescription = "流程触发器")]
        public string? FlowAction { get; set; }

        /// <summary>
        /// 通知触发器
        /// </summary>
        [NastyColumn(ColumnName = "NoticeAction", ColumnDescription = "通知触发器")]
        public string? NoticeAction { get; set; }

        /// <summary>
        /// 是否发布
        /// </summary>
        [NastyColumn(ColumnName = "IsPublish", ColumnDescription = "是否发布")]
        public bool IsPublish { get; set; }



        public override void OnPreAdd()
        {
            base.OnPreAdd();
            var db = AppSession.CurrentDb.Value;

            //初始化节点
            InitNodes();
        }

        public void InitNodes()
        {
            var empty = new List<string>();
            var start = new FlowConfigNode()
            {
                FlowConfigId = this.Id,
                Name = "开始",
                Code = "Start",
                PositionX = 50,
                PositionY = 50,
                PreNodeCodes = empty,
                RejectNodeCode = string.Empty,

            };

            var end = new FlowConfigNode()
            {
                FlowConfigId = this.Id,
                Name = "结束",
                Code = "End",
                PositionX = 400,
                PositionY = 50,
                PreNodeCodes = empty,
                RejectNodeCode = string.Empty,
            };

            var db = AppSession.CurrentDb.Value;
            db.Add(start);
            db.Add(end);
        }


        public override void OnPreUpdate()
        {
            base.OnPreUpdate();
            if (this.IsPublish) throw new Exception("已发布，不允许修改");

            var db = AppSession.CurrentDb.Value;
        }

        public override void OnPreDelete()
        {
            base.OnPreDelete();
            if (this.IsPublish) throw new Exception("已发布，不允许删除");

            var db = AppSession.CurrentDb.Value;
            //删除节点
            db.Deleteable<FlowConfigNode>().Where(t => t.FlowConfigId == this.Id).ExecuteCommand();
        }
    }
}
